define([
  'text!../../tmpl/tasks/index.html',
  './task',
  '../../collection/tasks',
  './edit',
  'underscore'
], function(tmpl, TaskView, Tasks, TaskEditView, _) {
  var TasksIndexView = Backbone.View.extend({
    tagName: 'div',
    className: 'row',

    template: _.template(tmpl),

    events: {
      'submit .add-task': 'addTask'
    },

    initialize: function() {
      this.children = [];
      this.collection.on('add', this.renderTask, this);
    },

    addTask: function() {
      var $input = this.$el.find('input[name="title"]');
      //this.modal 是传入的一条微博
      var task = new this.collection.model({id: this.model.get('id')});
      var self = this;

      task.save({comment: $input.val()}, {
        success: function() {
          self.collection.add(task, {at: 0});
        }
      });
      $input.val('');
      return false;
    },

    editTask: function(task) {
      if (this.taskEditView) {
        this.taskEditView.remove();
      }
      this.taskEditView = new TaskEditView({ model: task });
      this.$el.find('#selected-task').append(this.taskEditView.render().el);
    },

    renderTask: function(task, list, options) {
      var item = new TaskView({model: task, parentView: this});
      var $el = this.$el.find('#task-list');

      if (options && options.at === 0) {
        $el.prepend(item.render().el);
      } else {
        $el.append(item.render().el);
      }

      this.children.push(item);

    },

    render: function() {
      this.$el.html(this.template());

      var $el = this.$el.find('#task-list');
      var self = this;

      this.collection.fetch({
        data: {
          id: this.model.get('id')
        },
        success: function() {
          self.collection.each(function(task) {
            task.set('tasklist', self.model.get('id'));
          });
        }
      });

      return this;
    }
  });

  return TasksIndexView;
});